﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SignalRServer;

namespace WYFast.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});

            services.AddSignalR();
            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            #region IdentityServer4 服务端

            // 使用内存存储，密钥，客户端和资源来配置身份服务器。

            //services.AddIdentityService();
            //services.
            #endregion

            #region IdentityServer4  客户端

            //配置authorrize
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options => options.LoginPath = new PathString("/web/login"));
            #endregion

            services.AddMvc().AddRazorOptions(opt =>
            {
                opt.ViewLocationFormats.Clear();// 清空默认的列表
                opt.ViewLocationFormats.Add("/Areas/Web/Views/{0}" + RazorViewEngine.ViewExtension);
                opt.ViewLocationFormats.Add("/Areas/Web/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                opt.ViewLocationFormats.Add("/Areas/Web/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
                opt.ViewLocationFormats.Add("/Areas/{2}/{1}/{0}" + RazorViewEngine.ViewExtension);
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {

                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            //RequestDelegate handler = async context => await context.Response.WriteAsync("Unhandled exception occurred!");
            //app.UseExceptionHandler(new ExceptionHandlerOptions { ExceptionHandler = handler })
            //            .Run(context =>
            //                Task.FromException(new InvalidOperationException("自定义 exception...")
            //            ));

            //添加用户验证中间件
            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();


            app.RegSignalR();

            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Main}/{action=Index}/{id?}"
                );
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


        }
    }
}
